# !/usr/bin/env python
# -*- coding: utf-8 -*-

import logging.config
import os

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options

from conf import config
from conf.logging import LOGGING_DICT_CONFIG
from handlers.urls import handlers
from util.network import get_lan_ip

define("port", default=config.PORT, help="run on the given port", type=int)


class Application(tornado.web.Application):
    def __init__(self):
        app_handlers = handlers
        app_settings = {
            "template_path": os.path.join(config.BASE_DIR, "templates"),
            "static_path": os.path.join(config.BASE_DIR, "../frontend/static"),
            "media_path": os.path.join(config.BASE_DIR, "media"),
            "cookie_secret": config.COOKIE_SECRET,
            "xsrf_cookies": config.XSRF_COOKIES,
            "debug": config.DEBUG,
            "static_url_prefix": '/static/',
        }
        tornado.web.Application.__init__(self, app_handlers, **app_settings)


if __name__ == '__main__':
    print("start at http://%s:%s" % (get_lan_ip(), options.port))

    # Tornado Web Server
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application(), xheaders=True)
    http_server.listen(options.port)

    # 日志配置
    logging.config.dictConfig(LOGGING_DICT_CONFIG)
    logging.getLogger("requests").setLevel(logging.ERROR)
    logging.getLogger("kazoo").setLevel(logging.ERROR)

    io_loop = tornado.ioloop.IOLoop.current()
    # 当IOLoop阻塞3000ms会打印调用栈 - 5.0 deprecated, use PYTHONASYNCIODEBUG=1 instead
    # io_loop.set_blocking_log_threshold(3)
    # IOLoop Start
    io_loop.start()
